/**
 * 路由相关工具函数
 */

/**
 * 检查URL是否包含协议头
 */
export function hasOrigin(url: string): boolean {
  return /^https?:\/\//.test(url);
}

/**
 * 获取URL查询参数
 */
export function getQueryString(name: string, url?: string): string | null {
  const targetUrl = url || window.location.href;
  const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i');
  const results = regex.exec(targetUrl);
  return results && results[1] ? decodeURIComponent(results[1]) : null;
}

/**
 * 向URL添加查询参数
 */
export function addQueryToUrl(
  url: string,
  params: Record<string, any>
): string {
  if (!params || Object.keys(params).length === 0) {
    return url;
  }

  const separator = url.includes('?') ? '&' : '?';
  const queryString = Object.entries(params)
    .filter(([_, value]) => value !== undefined && value !== null)
    .map(
      ([key, value]) =>
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    )
    .join('&');

  return queryString ? `${url}${separator}${queryString}` : url;
}

/**
 * 替换URL中的环境标识
 */
export function replaceUrlEnv(url: string, env: string): string {
  // 替换环境相关的域名部分
  if (env === 'dev') {
    return url.replace(
      /https?:\/\/m\.xinli001\.com/,
      'https://m-dev.xinli001.com'
    );
  } else if (env === 'test') {
    return url.replace(
      /https?:\/\/m\.xinli001\.com/,
      'https://m-test.xinli001.com'
    );
  }
  return url;
}

/**
 * 获取运行时路由查询参数
 */
export function getRunWithRouteQuerys(): Record<string, any> {
  const params: Record<string, any> = {};

  // 从当前URL获取一些通用参数
  const urlParams = new URLSearchParams(window.location.search);

  // 添加一些常用的传递参数
  const commonParams = [
    'channel_flag',
    'cid',
    'source',
    'utm_source',
    'utm_medium',
    'utm_campaign',
  ];

  commonParams.forEach(param => {
    const value = urlParams.get(param);
    if (value) {
      params[param] = value;
    }
  });

  return params;
}
